<template>
  <div id="testPaper">
    <Breadcrumb content="考试列表" />
    <div class="bodyContent">
      <Splitpanes class="area">
        <Pane size="40">
          <vxe-toolbar perfect>
            <template #buttons>
              <vxe-input style="width: 180px" v-model="searchForm.keyWord" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="getTestPaperList" @search-click="getTestPaperList"></vxe-input>
              <el-select v-model="searchForm.paperType" @change="getTestPaperList" placeholder="考试类型" style="width: 200px">
                <el-option v-for="item in paperTypeOptions" :key="item.value" :label="item.name" :value="item.value" />
              </el-select>
              <vxe-button type="text" icon="vxe-icon-refresh" class="button-blue" content="刷新" @click="getTestPaperList" :loading="showLoading"></vxe-button>
            </template>
          </vxe-toolbar>
          <div class="testPaperTableBox">
            <vxe-table ref="testPaperTableRef" :loading="showLoading" class="mytable-scrollbar" border align="left" height="auto" :keep-source="true" :data="testPaperList" :row-config="{ isCurrent: true, isHover: true }" resizable show-overflow>
              <vxe-column type="checkbox" align="center" width="26"></vxe-column>
              <vxe-column type="seq" title="序号" align="center" width="30"></vxe-column>
              <vxe-column field="testCode" title="试卷编码" width="60"></vxe-column>
              <vxe-column field="testTitle" title="试卷标题"></vxe-column>
              <vxe-column field="startDate" title="开始时间"></vxe-column>
              <vxe-column field="endDate" title="结束时间"> </vxe-column>
              <vxe-column field="duration" title="考试时长"> </vxe-column>
              <vxe-column field="totalScore" title="总分"> </vxe-column>
              <vxe-column field="score" title="分数"> </vxe-column>
              <vxe-column field="userName" title="考试人"> </vxe-column>
              <vxe-column field="seq" title="顺序" width="50"> </vxe-column>
              <vxe-column field="paperType" title="考试类型">
                <template #default="{ row }">
                  {{ formatterPaperType(row.paperType) }}
                </template>
              </vxe-column>
              <vxe-column field="isSign" title="是否考试" width="90">
                <template #default="{ row }">
                  <el-tag size="small"> {{ formatterType(row.isSign) }}</el-tag>
                </template>
              </vxe-column>
              <vxe-column title="操作" width="100" show-overflow>
                <template #default="{ row }">
                  <vxe-button type="text" status="primary" icon="vxe-icon-file-txt" :content="row.isSign === 0 ? '开始考试' : '试卷预览'" @click="startTest(row)"></vxe-button>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
          <vxe-modal v-model="testPaperModel" title="考试" resize fullscreen :show-close="currentRow.isSign === 1">
            <div class="testPaperModalBox">
              <div class="bodyContent">
                <Splitpanes class="area">
                  <Pane size="30" class="leftPaperBox">
                    <div class="paperBigTitle">{{ '(' + paperInfo.testCode + ')' + paperInfo.testTitle }}</div>
                    <div class="restTime">
                      <vxe-icon name="time" status="danger"></vxe-icon>
                      <span>剩余时间</span>
                    </div>
                    <div class="countDown">{{ countdown }}</div>
                    <div class="topicBox">
                      <div class="nameOrg">
                        <span class="name">姓名：{{ currentRow.userName }}</span>
                        <span class="orgName">考试时长：{{ currentRow.duration }}分钟</span>
                      </div>
                      <div class="totalTopics">总分：{{ currentRow.totalScore }}</div>
                      <div class="topicList" v-for="bigItem in paperInfo.wkTestBigList" :key="bigItem.id">
                        <div class="topicTitle">{{ bigItem.title }}：{{ bigItem.description ? bigItem.description : '' }}</div>
                        <div class="topicListNumbers">
                          <span class="numberSpan" v-for="smallItem in bigItem.testSmallList" :key="smallItem.id">
                            <el-button v-if="smallItem.isCheck" tag="div" role="button" @click="scrollToSection(smallItem.id)" tabindex="0" type="primary"> {{ smallItem.seq }} </el-button>
                            <el-button v-else tag="div" role="button" tabindex="0" @click="scrollToSection(smallItem.id)"> {{ smallItem.seq }} </el-button>
                          </span>
                        </div>
                      </div>
                    </div>
                  </Pane>
                  <Pane size="70" class="rightPaperBox">
                    <el-scrollbar style="height: 100%">
                      <el-card v-for="(bigItem, bigItemIndex) in paperInfo.wkTestBigList" :key="bigItem.id">
                        <template #header>
                          <div class="card-header">
                            <span class="bigTitles">{{ bigItem.title }}：{{ bigItem.description ? bigItem.description : '' }}</span>
                          </div>
                        </template>
                        <div class="smallTopics" :id="smallItem.id" v-for="(smallItem, smallItemIndex) in bigItem.testSmallList" :key="smallItem.id">
                          <div class="smallTitles">
                            <span v-if="smallItem.showTrueOption != smallItem.checkOption" style="color: red">{{ smallItem.seq }} . {{ smallItem.questionName }}</span>
                            <span v-else>{{ smallItem.seq }} . {{ smallItem.questionName }}</span>
                            <span v-if="smallItem.showTrueOption" style="color: red"> (正确答案： {{ smallItem.showTrueOption }})</span>
                          </div>
                          <div class="singleJudgeOptions" v-if="smallItem.questionType === 'single' || smallItem.questionType === 'judge'">
                            <el-radio-group v-model="smallItem.checkOption" class="ml-4">
                              <el-radio v-for="option in smallItem.wkTestOptions" @change="checkChange(smallItem, bigItemIndex, smallItemIndex)" :disabled="disable" :label="option.optionValue" :key="option.id" :value="option.optionValue" size="small">{{ option.optionValue + '.' + option.optionContent }}</el-radio>
                            </el-radio-group>
                          </div>
                          <div class="multipleOptionsDiv" v-if="smallItem.questionType === 'multiple'">
                            <div class="multipleOptions">
                              <el-checkbox-group class="multipleOptions" v-model="smallItem.checkOptions">
                                <el-checkbox v-for="option in smallItem.wkTestOptions" :key="option.id" @change="checkChange(smallItem, bigItemIndex, smallItemIndex)" :disabled="disable" :label="option.optionValue" :value="option.optionValue + '.' + option.optionContent" size="small">{{ option.optionValue + '.' + option.optionContent }}</el-checkbox>
                              </el-checkbox-group>
                            </div>
                          </div>
                          <div v-if="smallItem.questionType === 'fill' || smallItem.questionType === 'answer'">
                            <vxe-input style="margin-left: 20px" v-model="smallItem.wkTestValue" @change="checkChange(smallItem, bigItemIndex, smallItemIndex)" :disabled="disable" placeholder="填写答案" size="small"></vxe-input>
                          </div>
                        </div>
                      </el-card>
                      <vxe-button v-if="currentRow.isSign === 0" type="text" style="margin-left: 50%" class="button-blue" icon="vxe-icon-check" content="交卷" @click="submitPaper()"></vxe-button>
                    </el-scrollbar>
                  </Pane>
                </Splitpanes>
              </div>
            </div>
          </vxe-modal>
        </Pane>
      </Splitpanes>
    </div>
  </div>
</template>

<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, onUnmounted, computed, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示信息
import { AppStore } from '@/stores/store';
import { VXETable, VxeModalDefines } from 'vxe-table';
import { ElMessageBox } from 'element-plus';

let store = AppStore();
let { proxy }: any = getCurrentInstance();
//根据关键字搜索
let searchForm = reactive({
  keyWord: '',
  year: null,
  paperType: null
});
let showLoading = ref(false); //表格加载状态
const testPaperList = reactive([]); //表格数据

//是否考试状态
const typeOptions = reactive([
  {
    name: '否',
    value: 0
  },
  {
    name: '是',
    value: 1
  }
]);
let testPaperModel = ref(false); //开始考试 弹框展开状态
let paperInfo = reactive({
  id: '',
  testCode: '',
  testTitle: '',
  startDate: '',
  endDate: '',
  totalScore: '',
  isSign: 0,
  seq: 0,
  sysUserList: [],
  remake: '',
  wkTestBigList: [],
  userId: ''
});
let currentRow = reactive({
  id: '',
  userName: '',
  duration: 0,
  totalScore: ''
});
// 考试类型
const paperTypeOptions = reactive([
  {
    name: '试剂考试',
    value: 0
  },
  {
    name: '体检考试',
    value: 1
  },
  {
    name: '检验考试',
    value: 2
  }
]);
const countdown = ref('00:00:00');
const intervalId = ref(null);
const targetTime = ref(); // 设置目标时间
const disable = ref(false);

onUnmounted(() => {
  if (intervalId.value) {
    clearInterval(intervalId.value);
  }
});

// 方法定义区 =============================================================
onMounted(() => {
  getTestPaperList();
});

// 获取列表信息
function getTestPaperList() {
  showLoading.value = true;
  testPaperList.length = 0;
  const url = '/wk/test/paper/getTestPaperListByUserId';
  proxy.$http
    .get(url, { params: { userId: store.userInfo.id, keyWord: searchForm.keyWord, paperType: searchForm.paperType } })
    .then((res: any) => {
      if (res.data && res.data.length > 0) {
        testPaperList.push(...res.data);
        const $xTable = proxy.$refs.testPaperTableRef as any;
        if ($xTable) {
          $xTable.setCurrentRow(testPaperList[0]);
        }
      }
      showLoading.value = false;
    })
    .catch((err: any) => {
      showLoading.value = false;
      proxy.$alert(err, '提示');
    });
}

//是否考试状态 格式化
function formatterType(cellValue) {
  const item = typeOptions.find((item) => item.value === cellValue);
  return item ? item.name : '';
}

//点击开始考试出现弹框
function startTest(row: any) {
  testPaperModel.value = true;
  Object.assign(currentRow, row);
  if (row.isSign === 1) {
    getPaperListView(row);
    // 停止定时器
    clearInterval(intervalId.value);
    countdown.value = '00:00:00';
    disable.value = true;
  } else {
    disable.value = false;
    getPaperView(row);
    const initNow = new Date();
    targetTime.value = initNow.setMinutes(initNow.getMinutes() + currentRow.duration);
    intervalId.value = setInterval(() => {
      const now = new Date();
      const distance = targetTime.value - now;
      if (distance >= 0) {
        const hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
        const minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
        const seconds = Math.floor((distance % (1000 * 60)) / 1000);
        countdown.value = `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
      } else {
        clearInterval(intervalId.value);
      }
    }, 1000);
  }
}

// 试卷信息
function getPaperView(currenPaperInfo: any) {
  const url = '/wk/test/paper/getPaperView';
  proxy.$http
    .get(url, { params: { paperId: currenPaperInfo.id } })
    .then((res: any) => {
      if (res.status.code === 1) {
        Object.assign(paperInfo, res.data);
      } else {
        VxeMessage('查询失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 查询试卷信息和答案信息
function getPaperListView(currenPaperInfo: any) {
  const url = '/wk/test/paper/getPaperListView';
  proxy.$http
    .get(url, { params: { paperId: currenPaperInfo.id } })
    .then((res: any) => {
      if (res.status.code === 1) {
        Object.assign(paperInfo, res.data);
        // 显示正确答案
        trueOption();
      } else {
        VxeMessage('查询失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 回显正确答案
function trueOption() {
  let newWkTestBigList = paperInfo.wkTestBigList.map((big) => {
    if (big.testSmallList && big.testSmallList.length > 0) {
      let newTestSmallList = big.testSmallList.map((small) => {
        if (small.wkTestOptions && small.wkTestOptions.length > 0) {
          if (small.questionType === 'single' || small.questionType === 'judge') {
            let trueOption = small.wkTestOptions.find((option) => option.isCorrect === 1);
            small.showTrueOption = trueOption.optionValue;
          } else if (small.questionType === 'multiple') {
            let trueOptions = small.wkTestOptions.filter((option) => option.isCorrect === 1);
            small.showTrueOption = trueOptions.map((item) => item.optionValue).join(',');
            small.checkOptions = small.checkOption ? [...small.checkOption.split(',')] : '';
          } else if (small.questionType === 'fill' || small.questionType === 'answer') {
            small.showTrueOption = small.wkTestOptions.map((item) => item.optionKeyword).join(',');
            small.wkTestValue = small.checkOption;
          }
        }
        return small;
      });
      big.testSmallList = newTestSmallList;
    }
    return big;
  });
  paperInfo.wkTestBigList = newWkTestBigList;
}

// 修改状态事件
function checkChange(smallItem: any, bigItemIndex: any, smallItemIndex: any) {
  if (smallItem.questionType === 'multiple' && smallItem.optionValue) {
    paperInfo.wkTestBigList[bigItemIndex].testSmallList[smallItemIndex].checkOptions.push(smallItem.optionValues);
  }
  paperInfo.wkTestBigList[bigItemIndex].testSmallList[smallItemIndex].isCheck = true;
}

// 交卷
function submitPaper() {
  paperInfo.userId = store.userInfo.id;
  const url = '/wk/test/paper/saveTestPaperUser';
  proxy.$http
    .post(url, paperInfo)
    .then((res: any) => {
      if (res.status.code === 1) {
        VxeMessage('交卷成功', VxeNotifyType.success);
        testPaperModel.value = false;
      } else {
        VxeMessage('交卷失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      proxy.$alert(err, '提示');
    });
}

// 定位到具体题目位置
function scrollToSection(sectionIndex: any) {
  const el = document.getElementById(`${sectionIndex}`);
  if (el) {
    el.scrollIntoView({ behavior: 'smooth' });
  }
}
// 格式化左侧试卷表格状态
function formatterPaperType(cellValue) {
  const item = paperTypeOptions.find((item) => item.value === cellValue);
  return item ? item.name : '';
}

// 关闭确认
// async function beforeHideMethod() {
//   if (currentRow.isSign === 1) {
//     return;
//   }
//   const type = await VXETable.modal.confirm('关闭考试不会记录您的答题信息，您确定要关闭考试吗？');
//   if (type !== 'confirm') {
//     return new Error();
//   }
// }
</script>

<style lang="scss" scoped>
#testPaper {
  height: 100%;
  .bodyContent {
    height: calc(100% - 60px);
    .area {
      background-color: $base-white;
      // 附加按钮间距
      .button-blue,
      .button-red {
        margin: 5px 0 5px 5px;
      }
      .testPaperTableBox {
        height: calc(100% - 40px);
      }
    }
    :deep(.vxe-modal--content) {
      padding: 0;
      .testPaperModalBox {
        height: 100%;
        .bodyContent {
          height: calc(100% - 20px);
          .leftPaperBox {
            padding: 15px;
            height: calc(100% - 30px);
            .paperBigTitle {
              text-align: center;
              font-size: 20px;
              font-weight: 700;
              color: #1a1f2e;
              margin: 10px;
            }
            .restTime {
              text-align: center;
              color: #458cfc;
              font-size: 20px;
              font-weight: 600;
              margin: 10px 0 0 0;
            }
            .countDown {
              text-align: center;
              color: #458cfc;
              font-size: 48px;
              font-weight: 700;
            }
            .topicBox {
              padding: 10px 30px 20px 20px;
              .nameOrg,
              .totalTopics {
                font-size: 16px;
                font-weight: 700;
                color: #1a1f2e;
                display: flex;
                align-items: center;
                justify-content: space-between;
              }
              .topicList {
                font-size: 16px;
                font-weight: 700;
                color: #1a1f2e;
                margin: 10px 0 0 0;
                .topicTitle {
                  margin: 0 0 5px 0;
                }
                .topicListNumbers {
                  .numberSpan {
                    margin: 5px 10px 5px 0;
                    display: inline-block;
                    .el-button {
                      width: 38px;
                      height: 24px;
                    }
                  }
                }
              }
            }
          }
          .rightPaperBox {
            height: 100%;
            .el-card {
              margin: 0 10px 10px 0;
              .bigTitles {
                font-size: 17px;
                font-weight: 700;
                color: #1a1f2e;
              }
              .smallTopics {
                color: #1a1f2e;
                margin-bottom: 5px;
                .smallTitles {
                  font-size: 16px;
                }
                .singleJudgeOptions {
                  .el-radio-group {
                    display: block;
                    .el-radio {
                      display: block;
                      font-size: 15px;
                      margin: 0 0 5px 10px;
                      .el-radio__label {
                        font-size: 16px;
                      }
                    }
                  }
                }
                .multipleOptionsDiv {
                  font-size: 15px;
                  margin: 0 0 5px 10px;
                  .multipleOptions {
                    font-size: 15px;
                    margin: 0 0 5px 10px;
                    .el-checkbox {
                      display: block;
                      margin: 5px 0 0 0;
                      .el-checkbox__label {
                        font-size: 16px;
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}
</style>
